<template>
  <div class="app-container">
    <el-tabs v-model="status" type="card" @tab-click="handleClickStatus">
      <el-tab-pane name="-1">
        <span slot="label">
          <i class="el-icon-s-order"></i> 全部订单
        </span>
      </el-tab-pane>
      <el-tab-pane name="1">
        <span slot="label">
          <i class="el-icon-document"></i> 待处理
        </span>
      </el-tab-pane>
      <el-tab-pane name="3">
        <span slot="label">
          <i class="el-icon-document"></i> 已完成
        </span>
      </el-tab-pane>
      <el-tab-pane name="5">
        <span slot="label">
          <i class="el-icon-circle-close"></i> 已取消
        </span>
      </el-tab-pane>
    </el-tabs>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :rules="queryRules"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          maxlength="40"
          show-word-limit
          clearable
          class="inputClass"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          show-word-limit
          clearable
          class="inputClass"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车架号" prop="vin">
        <el-input
          v-model="queryParams.vin"
          placeholder="请输入车架号"
          maxlength="17"
          show-word-limit
          clearable
          class="inputClass"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车型名称" prop="modelName">
        <!--<el-input-->
          <!--v-model="queryParams.modelName"-->
          <!--placeholder="请输入车型名称"-->
          <!--maxlength="40"-->
          <!--show-word-limit-->
          <!--clearable-->
          <!--class="inputClass"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->

        <el-select
          v-model="queryParams.modelName"
          placeholder="请选择"
          filterable
          clearable
          style="width: 240px"
          @change="onSelectChange"
        >
          <el-option
            v-for="item in carModelList"
            :key="item.modelCode"
            :label="item.modelName"
            :value="item.modelName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单来源" prop="orderSource">
        <el-select v-model="queryParams.orderSource" placeholder="请选择订单来源" clearable>
          <el-option
            v-for="dict in dict.type.order_source"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="激活状态" prop="activeStatus">
        <el-select v-model="queryParams.activeStatus" placeholder="请选择激活状态" clearable>
          <el-option
            v-for="dict in dict.type.order_active_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="商品名称" prop="softwareName">
        <el-input
          v-model="queryParams.softwareName"
          placeholder="请输入商品名称"
          maxlength="40"
          show-word-limit
          clearable
          class="inputClass"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label="软件包功能项" prop="softwareFunction">
        <el-input
          v-model="queryParams.softwareFunction"
          placeholder="请输入软件包功能项"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <!--<el-form-item label="购买规格" prop="softwareSpec">-->
        <!--<el-input-->
          <!--v-model="queryParams.softwareSpec"-->
          <!--placeholder="请输入购买规格"-->
          <!--maxlength="40"-->
          <!--show-word-limit-->
          <!--clearable-->
          <!--class="inputClass"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</el-form-item>-->

      <el-form-item label="商品类目" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入商品类目"
          maxlength="40"
          show-word-limit
          clearable
          class="inputClass"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload"
          size="mini"
          :disabled="multiple"
          @click="batchClose()"
          v-hasPermi="['shop:order:edit']"
        >批量关闭</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['shop:order:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          v-hasPermi="['shop:order:query']"
          @click="handleUpdateOrderStatus"
        >批量更新订单状态</el-button>
      </el-col>
      <!--<el-col :span="1.5">-->
        <!--<el-button-->
          <!--type="info"-->
          <!--plain-->
          <!--icon="el-icon-upload2"-->
          <!--size="mini"-->
          <!--@click="handleImport"-->
          <!--v-hasPermi="['system:user:import']"-->
        <!--&gt;导入</el-button>-->
      <!--</el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="tableColumns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!-- <el-table-column label="主键" align="center" prop="id" v-if="false" /> -->
      <el-table-column
        label="订单号"
        align="center"
        prop="orderNo"
        key="orderNo"
        v-if="tableColumns[0].visible"
        width="110"
      />
      <el-table-column
        label="商品类目"
        align="center"
        prop="categoryName"
        key="categoryName"
        v-if="tableColumns[1].visible"
        width="80"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.categoryId?JSON.parse(scope.row.categoryId)['name']:''  }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="商品名称"
        align="center"
        prop="name"
        key="name"
        v-if="tableColumns[2].visible"
      />
      <el-table-column
        label="服务功能项"
        align="center"
        prop="softwareFunction"
        key="softwareFunction"
        v-if="tableColumns[3].visible"
      >
        <template
          slot-scope="scope"
          v-if="scope.row.softwareFunction"
        >{{ scope.row.softwareFunction }}</template>
      </el-table-column>
      <el-table-column
        label="购买规格"
        align="center"
        prop="softwareSpec"
        key="softwareSpec"
        v-if="tableColumns[4].visible"
      >
        <template slot-scope="scope">
          <span>{{ isJSON(scope.row.softwareSpec)?JSON.parse(scope.row.softwareSpec)['supplierName']:scope.row.softwareSpec }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="用户ID"
        align="center"
        prop="userId"
        key="userId"
        v-if="tableColumns[5].visible"
      />
      <el-table-column
        label="支付流水号"
        align="center"
        prop="transactionId"
        key="transactionId"
        v-if="tableColumns[6].visible"
      />
      <el-table-column
        label="支付方式"
        align="center"
        prop="paymentType"
        key="paymentType"
        v-if="tableColumns[7].visible"
      >
        <template slot-scope="scope">
          <span v-if="!scope.row.paymentType || scope.row.paymentType.length == 0">-</span>
          <dict-tag v-else :options="dict.type.pay_type" :value="item" v-for="(item,index) in scope.row.paymentType.split(',')" :key="index"/>
        </template>
      </el-table-column>
      <el-table-column
        width="100"
        label="订单来源"
        align="center"
        prop="orderSource"
        key="orderSource"
        v-if="tableColumns[8].visible"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_source" :value="scope.row.orderSource"/>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="isPay"
        key="isPay"
        width="230"
        v-if="tableColumns[9].visible"
      >
        <template slot-scope="scope">
          <div class="grid-content flex-content">
            订单状态：
            <dict-tag :options="dict.type.order_status" :value="scope.row.status"/>
          </div>
          <div class="grid-content flex-content">
          <!--<div class="grid-content flex-content">-->
            激活状态：
            <dict-tag :options="dict.type.order_active_status" :value="scope.row.activeStatus"/>
          </div>
          <!--<div class="grid-content flex-content" v-if="scope.row.memberType!='0'">-->
          <!--&lt;!&ndash;<div class="grid-content flex-content">&ndash;&gt;-->
            <!--充值状态：-->
            <!--<dict-tag :options="dict.type.order_recharge_status" :value="scope.row.activeStatus"/>-->
          <!--</div>-->
          <div class="grid-content flex-content">
            现金支付状态：
            <span v-if="!scope.row.cashPayStatus">-</span>
            <dict-tag v-else :options="dict.type.order_is_pay" :value="scope.row.cashPayStatus"/>
          </div>
          <div class="grid-content flex-content">
            积分支付状态：
            <span v-if="!scope.row.integralPayStatus">-</span>
            <dict-tag v-else :options="dict.type.order_is_pay" :value="scope.row.integralPayStatus"/>
          </div>
          <div class="grid-content flex-content">
            开票状态：
            <dict-tag :options="dict.type.order_is_makeout" :value="scope.row.isMakrout"/>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="金额（￥）"
        align="center"
        prop="salesPrice"
        key="salesPrice"
        min-width="150"
        v-if="tableColumns[10].visible"
      >
        <template slot-scope="scope">
          <div style="text-align: left">
            <!-- <div class="grid-content">
              商品价格：￥{{ scope.row.salesPrice }}
            </div>-->
            <div class="grid-content">商品价格：￥{{ scope.row.goodsPrice }}</div>
            <div class="grid-content" :style="{color: scope.row.payCash ==0?'red':''}">实付现金：￥{{ scope.row.payCash == '0' ? '0.00': scope.row.payCash }}</div>
            <div class="grid-content" :style="{color: scope.row.payIntegral ==0?'red':''}">实付积分：{{ scope.row.payIntegral }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="车架号"
        align="center"
        prop="vin"
        key="vin"
        min-width="160"
        v-if="tableColumns[11].visible"
      />

      <el-table-column
        label="时间"
        align="center"
        prop="paymentTime"
        key="paymentTime"
        width="120"
        v-if="tableColumns[12].visible"
      >
        <template slot-scope="scope">
          <div class="grid-content" v-if="scope.row.createDate">
            <div>创建时间：</div>
            <div>{{ parseTime(scope.row.createDate, "{y}-{m}-{d}") }}</div>
          </div>
          <div class="grid-content" v-if="scope.row.paymentTime">
            <div>付款时间：</div>
            <div>{{ parseTime(scope.row.paymentTime, "{y}-{m}-{d}") }}</div>
          </div>
          <div class="grid-content" v-if="scope.row.lastUpdateDate">
            <div>最后更新时间：</div>
            <div>{{ parseTime(scope.row.lastUpdateDate, "{y}-{m}-{d}") }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="120"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            v-hasPermi="['shop:order:query']"
            @click="handleCheckOrder(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:order:edit']"
            v-if="scope.row.isPay == 0 && scope.row.status != 5 && scope.row.paymentPrice!= '0'"
          >改价</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRefund(scope.row)"
            v-hasPermi="['shop:order:edit']"
            v-if="
              scope.row.isPay == 1 &&
              scope.row.status != 5 &&
              scope.row.isRefund == 0
            "
          >退款</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCancel(scope.row)"
            v-hasPermi="['shop:order:edit']"
            v-if="scope.row.isPay == 0 && scope.row.status != 5"
          >取消</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileFail"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--<div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="this.submitFileBtn" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改价格对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" @submit.native.prevent>
        <el-form-item label="待支付金额（￥）" prop="paymentPrice" v-if="Number(resData.paymentPrice)!=0">
          <el-input-number
            v-model="form.paymentPrice"
            :precision="2"
            :step="0.1"
            :min="0.01"
            :max="99999999"
            placeholder="请输入订单金额"
          />
        </el-form-item>
        <el-form-item label="待支付积分" prop="orderIntegral" v-if="resData.orderIntegral">
          <span><span style="margin-right: 15px">{{ resData.orderIntegral || 0 }} </span><span>（ 积分部分不允许改价 ）</span></span>
        </el-form-item>
        <el-form-item label="请输入改价原因" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 手动退款对话框 -->
    <el-dialog :title="titlefund" :visible.sync="openfund" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rulesFund" label-width="140px" @submit.native.prevent>
        <el-form-item label="退款金额(￥)" prop="paymentPrice" v-if="Number(resData.paymentPrice)!=0">
          <el-input-number
            v-model="form.paymentPrice"
            :precision="2"
            :step="0.1"
            :min="0.01"
            placeholder="请输入退款金额"
          />
        </el-form-item>
        <el-form-item label="退款积分" prop="orderIntegral" v-if="resData.orderIntegral">
          <span><span style="margin-right: 15px">{{ resData.orderIntegral || 0 }} </span><span>（ 已付积分默认全部退还 ）</span></span>
        </el-form-item>
        <el-form-item label="请输入退款原因" prop="refundReason">
          <el-input v-model="form.refundReason"  type="textarea"  placeholder="请输入退款原因" @input="inputChangeTrigger"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitFormFund">确 定</el-button>
        <el-button @click="cancelFund">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  updatePay,
  closeOrder,
  refundAmount,
  cancelOrder,
  activeStatus,
} from "@/api/shop/order";
import {
  getModelListUrl,
} from "@/api/statistics/index.js";
import { getToken } from "@/utils/auth";
import { isJSON } from "@/utils/index";

export default {
  name: "Order",
  dicts: [
    "order_is_makeout",
    "order_is_pay",
    "order_status",
    "order_active_status",
    "order_recharge_status",
    "app_name_type",
    "order_payment_type",
    "order_source",
    "pay_type"
  ],
  data() {
    return {
      // table列筛选
      tableColumns: [
        { key: 0, label: `订单号`, visible: true },
        { key: 1, label: `商品类目`, visible: true },
        { key: 2, label: `商品名称`, visible: true },
        { key: 3, label: `服务功能项`, visible: true },
        { key: 4, label: `购买规格`, visible: true },
        { key: 5, label: `用户ID`, visible: true },
        { key: 6, label: `支付流水号`, visible: true },
        { key: 7, label: `支付方式`, visible: true },
        { key: 8, label: `订单来源`, visible: true },
        { key: 9, label: `状态`, visible: true },
        { key: 10, label: `积分支付状态`, visible: true },
        { key: 11, label: `金额`, visible: true },
        { key: 12, label: `车架号`, visible: true },
        { key: 13, label: `时间`, visible: true },
        { key: 14, label: `操作`, visible: true },
      ],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组
      closes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      submitFileBtn: false,
      // 总条数
      total: 0,
      // 订单主表表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      titlefund: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      openfund: false,
      status: "-1",
      // 用户导入参数
      upload: {
        // 是否显示弹出层（订单导入）
        open: false,
        // 弹出层标题（订单导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的订单数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/shop/order/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: undefined,
        name: undefined,
        appType: undefined,
        userId: undefined,
        vin: undefined,
        series: undefined,
        modelName: undefined,
        modelCode: undefined,
        paymentType: undefined,
        isPay: undefined,
        status: undefined,
        activeStatus: undefined,
        isMakrout: undefined,
        orderSource: undefined,
        salesPrice: undefined,
        paymentPrice: undefined,
        costPrice: undefined,
        paymentTime: undefined,
        userMessage: undefined,
        transactionId: undefined,
        createDate: undefined,
        lastUpdateDate: undefined,
        lastUpdateBy: undefined,
        deleteFlag: undefined,
        softName: undefined,
        softFunc: undefined,
        specification: undefined,
        softwareName: undefined,
        softwareSpec: undefined,
        categoryId:undefined,
        softwareFunction: undefined,
        startCreateDate: undefined,
        endCreateDate: undefined,
        ids: undefined,
        refundReason: undefined
      },
      //  查询参数校验
      queryRules: {
        orderNo: [
          {
            validator: (rule, value, callback) => {
              if (value.length > 0 && !new RegExp(/^\d{0,40}$/).test(value)) {
                this.queryParams.orderNo = undefined;
                callback(new Error("请输入正确的订单号"));
              } else if (value.length > 40) {
                callback(new Error("订单号的长度不能超过40"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        // userId: [
        //   {
        //     validator: (rule, value, callback) => {
        //       if (value.length > 0 && !new RegExp(/^\d{0,10}$/).test(value)) {
        //         this.queryParams.userId = undefined;
        //         callback(new Error("请输入正确的用户ID"));
        //       } else if (value.length > 10) {
        //         callback(new Error("用户Id的长度不能超过10"));
        //       } else {
        //         callback();
        //       }
        //     },
        //     trigger: "blur"
        //   }
        // ],
        vin: [
          {
            validator: (rule, value, callback) => {
              if (
                value.length > 0 &&
                !new RegExp(/^[A-HJ-NPR-Z\d]{0,17}$/).test(value)
              ) {
                this.queryParams.vin = undefined;
                callback(new Error("请输入正确的VIN"));
              } else if (value.length > 17) {
                callback(new Error("VIN的长度不能超过17"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
      // 接口数据
      resData:{},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        paymentPrice: [
          { required: true, message: "订单金额不能为空", trigger: "blur" }
        ],
      },
      // 表单校验
      rulesFund: {
        paymentPrice: [
          { required: true, message: "退款金额不能为空", trigger: "blur" }
        ],
        remark: [{ required: true, message: "备注不能为空", trigger: "blur" }]
      },
      carModelList: [],
    };
  },
  created() {
    this.getList();

    console.log("this.dict: ", this.dict);
  },
  async mounted() {
    await this.getCarModelList();
  },
  methods: {
    // changePaymentPrice(e){
    //   if(this.resData && this.resData.paymentPrice && this.resData.paymentPrice < e){
    //     this.form.paymentPrice = this.resData.paymentPrice
    //   }
    // },
    /**
     * 获取车型数据
     */
    getCarModelList() {
      return new Promise((resolve) => {
        getModelListUrl().then((res) => {
          if (res.data) {
            this.carModelList = res.data;
          }
          resolve(true);
        });

        // this.carModelList = res.data
      });
    },
    /**
     * 修改选项
     */
    onSelectChange(e) {
      if(!this.queryParams.modelName){
        this.queryParams.modelName = undefined;
      }
    },
    isJSON(str){
      return isJSON(str)
    },
    /** 查询订单主表列表 */
    getList() {
      this.loading = true;
      this.queryParams.ids = undefined;
      if (this.queryParams.status != undefined && this.queryParams.status != "") {
        this.status = this.queryParams.status;
      } else {
        this.status = "-1";
      }
      if (this.dateRange != "" && this.dateRange != null) {
        this.queryParams.startCreateDate = this.dateRange[0];
        this.queryParams.endCreateDate = this.dateRange[1];
      } else {
        this.queryParams.startCreateDate = undefined;
        this.queryParams.endCreateDate = undefined;
      }

      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancelFund() {
      this.openfund = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        orderNo: undefined,
        name: undefined,
        appType: undefined,
        userId: undefined,
        vin: undefined,
        series: undefined,
        modelName: undefined,
        modelCode: undefined,
        paymentType: undefined,
        isPay: undefined,
        status: undefined,
        activeStatus: undefined,
        isMakrout: undefined,
        orderSource: undefined,
        salesPrice: undefined,
        paymentPrice: undefined,
        costPrice: undefined,
        paymentTime: undefined,
        userMessage: undefined,
        transactionId: undefined,
        remark: undefined,
        createDate: undefined,
        createBy: undefined,
        lastUpdateDate: undefined,
        lastUpdateBy: undefined,
        deleteFlag: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.ids = undefined;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.queryParams.ids = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.closes = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改价格操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getOrder(id).then(response => {
        this.resData = response.data
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改订单价格";
      });
    },
    /** 退款操作 */
    handleRefund(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getOrder(id).then(response => {
        this.resData = JSON.parse(JSON.stringify(response.data))
        this.loading = false;
        this.form = JSON.parse(JSON.stringify(response.data))
        this.form.refundReason = "已协商退款";
        this.openfund = true;
        this.titlefund = "手动退款";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          updatePay({
            id: this.form.id,
            paymentPrice: this.form.paymentPrice,
            remark: this.form.remark
          })
            .then(response => {
              this.$modal.msgSuccess("修改价格成功");
              this.open = false;
              this.getList();
            })
            .finally(() => {
              this.buttonLoading = false;
            });
        }
      });
    },

    /** 提交按钮 */
    submitFormFund() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          refundAmount({
            id: this.form.id,
            paymentPrice: this.form.paymentPrice,
            refundReason: this.form.refundReason
          })
            .then(response => {
              this.$modal.msgSuccess("手动退款成功");
              this.openfund = false;
              this.getList();
            })
            .finally(() => {
              this.buttonLoading = false;
            });
        }
      });
    },
    /**
     * 查看按钮
     */
    handleCheckOrder(row) {
      this.$router.push({
        path: "/shop/order/detail",
        query: {
          id: row.id
        }
      });
    },
    /** 取消按钮操作 */
    handleCancel(row) {
      let ids = row.orderNo;
      this.$modal
        .confirm('是否确认取消订单号为"' + ids + '"的数据项？')
        .then(() => {
          this.loading = true;
          return cancelOrder({
            ids: ids
          });
        })
        .then(() => {
          this.loading = false;
          this.handleQuery();
          this.$modal.msgSuccess("取消订单成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleClickStatus(tab, event) {
      this.queryParams.pageNum = 1;
      this.status = tab.name;
      this.queryParams.status = this.status != "-1" ? this.status : null;
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.ids = undefined;
      if (this.ids.length > 0) {
        if (this.ids.length > 1000) {
          this.$message.error("勾选导出的数据不能超过一千条！");
          return false;
        }
        let selectionIds = "";
        this.ids.forEach(id => {
          selectionIds += id + ",";
        });
        if (selectionIds.length > 0) {
          selectionIds = selectionIds.substring(0, selectionIds.length - 1);
        }
        this.queryParams.ids = selectionIds;
      }
      this.download(
        "shop/order/export",
        {
          ...this.queryParams
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },
    handleUpdateOrderStatus() {
      if (this.closes.length > 0) {
        if (this.closes.length > 1000) {
          this.$message.error('勾选更新状态的数据不能超过一千条！');
          return false;
        }
        const selectionIds = [];
        this.closes.forEach((item) => {
          selectionIds.push(item.orderNo);
        });
        activeStatus({ orderNumberList: selectionIds }).then(() => {
          this.getList();
        });
      }
    },
    batchClose() {
      if (this.ids.length <= 0) {
        this.$message.error("请选择订单");
        return;
      }
      //
      for (let singleRow of this.closes) {
        if (singleRow.isPay == "1" || singleRow.status == "5") {
          this.$message.error("请正确选择未取消未支付订单");
          return;
        }
      }
      this.$prompt("请输入原因，反馈人员", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValidator: value => {
          if (!value) {
            return "请输入原因，反馈人员";
          }
        }
      }).then(({ value }) => {
        let selectionIds = "";
        this.ids.forEach(id => {
          selectionIds += id + ",";
        });
        closeOrder({
          ids: selectionIds,
          closeDetail: value
        }).then(data => {
          this.getList();
        });
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "shop/order/importTemplate",
        {},
        `order_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      var that = this;
      that.submitFileBtn = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.submitFileBtn = false;
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response.code == 999) {
        this.$message.error(response.message);
        return false;
      }
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.message +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    inputChangeTrigger() {
      this.$forceUpdate();
    },
     handleFileFail(response){
      this.submitFileBtn = false;
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          "数据正在导入，请稍候查看。【也可在操作日志里查看是否完成】" +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    }
  }
};
</script>
<style scoped>
.flex-content {
  display: flex;
  margin-bottom: 5px;
}

/* element-ui input style overload */
::v-deep .inputClass > input {
  padding-right: 70px;
}
</style>
